package com.smartbone.dao.daoImplemetation;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.context.ApplicationContext;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;

import com.smartbone.dao.daoInterface.IBandDAO;
import com.smartbone.entity.Band;

/**
 * A data access object (DAO) providing persistence and search support for Band
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see com.Band
 * @author MyEclipse Persistence Tools
 */

public class BandDAO extends JpaDaoSupport implements IBandDAO {
	// property constants
	public static final String START_PRICE = "startPrice";
	public static final String END_PRICE = "endPrice";
	public static final String DATE_NUM = "dateNum";
	public static final String BAND_PER = "bandPer";
	public static final String TJ_PRICE = "tjPrice";
	public static final String NOW_PRICE = "nowPrice";
	public static final String PRICE_DIF = "priceDif";
	public static final String TJ_AMOUNT = "tjAmount";
	public static final String NOW_AMOUNT = "nowAmount";
	public static final String AMOUNT_DIF = "amountDif";

	/**
	 * Perform an initial save of a previously unsaved Band entity. All
	 * subsequent persist actions of this entity should use the #update()
	 * method. This operation must be performed within the a database
	 * transaction context for the entity's data to be permanently saved to the
	 * persistence store, i.e., database. This method uses the
	 * {@link javax.persistence.EntityManager#persist(Object)
	 * EntityManager#persist} operation.
	 * <p>
	 * User-managed Spring transaction example:
	 * 
	 * <pre>
	 * TransactionStatus txn = txManager
	 * 		.getTransaction(new DefaultTransactionDefinition());
	 * BandDAO.save(entity);
	 * txManager.commit(txn);
	 * </pre>
	 * 
	 * @see <a href =
	 *      "http://www.myeclipseide.com/documentation/quickstarts/jpaspring#containermanaged">Spring
	 *      container-managed transaction examples</a>
	 * @param entity
	 *            Band entity to persist
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void save(Band entity) {
		logger.info("saving Band instance");
		try {
			getJpaTemplate().persist(entity);
			logger.info("save successful");
		} catch (RuntimeException re) {
			logger.error("save failed", re);
			throw re;
		}
	}

	/**
	 * Delete a persistent Band entity. This operation must be performed within
	 * the a database transaction context for the entity's data to be
	 * permanently deleted from the persistence store, i.e., database. This
	 * method uses the {@link javax.persistence.EntityManager#remove(Object)
	 * EntityManager#delete} operation.
	 * <p>
	 * User-managed Spring transaction example:
	 * 
	 * <pre>
	 * TransactionStatus txn = txManager
	 * 		.getTransaction(new DefaultTransactionDefinition());
	 * BandDAO.delete(entity);
	 * txManager.commit(txn);
	 * entity = null;
	 * </pre>
	 * 
	 * @see <a href =
	 *      "http://www.myeclipseide.com/documentation/quickstarts/jpaspring#containermanaged">Spring
	 *      container-managed transaction examples</a>
	 * @param entity
	 *            Band entity to delete
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void delete(Band entity) {
		logger.info("deleting Band instance");
		try {
			entity = getJpaTemplate().getReference(Band.class, entity.getId());
			getJpaTemplate().remove(entity);
			logger.info("delete successful");
		} catch (RuntimeException re) {
			logger.error("delete failed", re);
			throw re;
		}
	}

	/**
	 * Persist a previously saved Band entity and return it or a copy of it to
	 * the sender. A copy of the Band entity parameter is returned when the JPA
	 * persistence mechanism has not previously been tracking the updated
	 * entity. This operation must be performed within the a database
	 * transaction context for the entity's data to be permanently saved to the
	 * persistence store, i.e., database. This method uses the
	 * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge}
	 * operation.
	 * <p>
	 * User-managed Spring transaction example:
	 * 
	 * <pre>
	 * TransactionStatus txn = txManager
	 * 		.getTransaction(new DefaultTransactionDefinition());
	 * entity = BandDAO.update(entity);
	 * txManager.commit(txn);
	 * </pre>
	 * 
	 * @see <a href =
	 *      "http://www.myeclipseide.com/documentation/quickstarts/jpaspring#containermanaged">Spring
	 *      container-managed transaction examples</a>
	 * @param entity
	 *            Band entity to update
	 * @return Band the persisted Band entity instance, may not be the same
	 * @throws RuntimeException
	 *             if the operation fails
	 */
	public Band update(Band entity) {
		logger.info("updating Band instance");
		try {
			Band result = getJpaTemplate().merge(entity);
			logger.info("update successful");
			return result;
		} catch (RuntimeException re) {
			logger.error("update failed", re);
			throw re;
		}
	}

	public Band findById(Long id) {
		logger.info("finding Band instance with id: " + id);
		try {
			Band instance = getJpaTemplate().find(Band.class, id);
			return instance;
		} catch (RuntimeException re) {
			logger.error("find failed", re);
			throw re;
		}
	}

	/**
	 * Find all Band entities with a specific property value.
	 * 
	 * @param propertyName
	 *            the name of the Band property to query
	 * @param value
	 *            the property value to match
	 * @return List<Band> found by query
	 */
	@SuppressWarnings("unchecked")
	public List<Band> findByProperty(String propertyName, final Object value) {
		logger.info("finding Band instance with property: " + propertyName
				+ ", value: " + value);
		try {
			final String queryString = "select model from Band model where model."
					+ propertyName + "= :propertyValue";
			return getJpaTemplate().executeFind(new JpaCallback() {
				public Object doInJpa(EntityManager em)
						throws PersistenceException {
					Query query = em.createQuery(queryString);
					query.setParameter("propertyValue", value);
					return query.getResultList();
				}
			});
		} catch (RuntimeException re) {
			logger.error("find by property name failed", re);
			throw re;
		}
	}

	public List<Band> findByStartPrice(Object startPrice) {
		return findByProperty(START_PRICE, startPrice);
	}

	public List<Band> findByEndPrice(Object endPrice) {
		return findByProperty(END_PRICE, endPrice);
	}

	public List<Band> findByDateNum(Object dateNum) {
		return findByProperty(DATE_NUM, dateNum);
	}

	public List<Band> findByBandPer(Object bandPer) {
		return findByProperty(BAND_PER, bandPer);
	}

	public List<Band> findByTjPrice(Object tjPrice) {
		return findByProperty(TJ_PRICE, tjPrice);
	}

	public List<Band> findByNowPrice(Object nowPrice) {
		return findByProperty(NOW_PRICE, nowPrice);
	}

	public List<Band> findByPriceDif(Object priceDif) {
		return findByProperty(PRICE_DIF, priceDif);
	}

	public List<Band> findByTjAmount(Object tjAmount) {
		return findByProperty(TJ_AMOUNT, tjAmount);
	}

	public List<Band> findByNowAmount(Object nowAmount) {
		return findByProperty(NOW_AMOUNT, nowAmount);
	}

	public List<Band> findByAmountDif(Object amountDif) {
		return findByProperty(AMOUNT_DIF, amountDif);
	}

	/**
	 * Find all Band entities.
	 * 
	 * @return List<Band> all Band entities
	 */
	@SuppressWarnings("unchecked")
	public List<Band> findAll() {
		logger.info("finding all Band instances");
		try {
			final String queryString = "select model from Band model";
			return getJpaTemplate().executeFind(new JpaCallback() {
				public Object doInJpa(EntityManager em)
						throws PersistenceException {
					Query query = em.createQuery(queryString);
					return query.getResultList();
				}
			});
		} catch (RuntimeException re) {
			logger.error("find all failed", re);
			throw re;
		}
	}

	public static IBandDAO getFromApplicationContext(ApplicationContext ctx) {
		return (IBandDAO) ctx.getBean("BandDAO");
	}
}